var bcrypt = dcodeIO.bcrypt;      //use the bcrypt library

function signup() {
    // get the input that user typed
    const name = document.getElementById('newname').value;
    const email = document.getElementById('newemail').value;
    const password1 = document.getElementById('newpassword1').value;
    const password2 = document.getElementById('newpassword2').value;

    if (password1 === password2) {
		    // create a random salt value
		    // encrypt the password with the salt
		    const salt = bcrypt.genSaltSync(10);
		    const hashedPassword = bcrypt.hashSync(password1, salt);

		    // read the current users array
		    // push this user into the users array
		    users = JSON.parse(localStorage.getItem("users"));
		    if (users === null)    //if there are no users yet
			    users = [];          //initialize it to empty
		    users.push({ name, email, password: hashedPassword, count:0, history:[]});

            console.log(users);
		    
		    alert('User registered with hashed password.  Welcome ' + name);
		    
		    // save the newly updated users JSON to "database"
		    // redirect User back to Log In page 
		    localStorage.setItem("users", JSON.stringify(users));
		    window.location.href = "./login.html";   
		} else {
		   alert('Passwords do not match!');
		}
}

function login() {

    // read the "database" of users from local storage
    users = JSON.parse(localStorage.getItem("users"));
    
    // read the login email and password
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    
    // search JSON object to see if any user with this email exists
    // email is the primary search key for a user
    const user = users.find(u => u.email === email);

		// if exists, and the password matches
		// then successful login.
		// save this "loggedinUser" into local storage
    if (user && bcrypt.compareSync(password, user.password)) {
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        alert('Login successful!  for ' + user.name);
        window.location.href = "./main.html";
    } else {
        alert('Login failed.');
    }
}